<template>
<div class="tab-pane active" id="stream0-config">
    <form role="form" class="form-horizontal" autocomplete="off" @submit.prevent="onStream0Submit" data-vv-scope="stream0">
        <div :class="['form-group' , {'has-error': errors.has('stream0.gridSize')}]">
            <label for="stream0-grid-size" class="col-sm-3 control-label">分屏网格</label>
            <div class="col-sm-8">
                <select id="stream0-grid-size" name="gridSize" class="form-control" v-model.trim="gridSize" @change="onGridSizeChange">
                    <option v-for="(val, idx) in gridSizeList" :value="val" :key="idx">{{ val }}</option>
                </select>
                <span class="help-block">{{errors.first('stream0.gridSize')}}</span>
            </div>
        </div>
        <div :class="['form-group' , {'has-error': errors.has('stream0.videoSize')}]">
            <label for="stream0-video-size" class="col-sm-3 control-label">输出分辨率</label>
            <div class="col-sm-8">
                <select id="stream0-video-size" name="videoSize" class="form-control" v-model.trim="videoSize">
                    <option v-for="(val, idx) in videoSizeList" :value="val" :key="idx">{{ val }}</option>
                </select>
                <span class="help-block">{{errors.first('stream0.videoSize')}}</span>
            </div>
        </div>
        <div :class="['form-group' , {'has-error': errors.has('stream0.VideoFramerate')}]">
            <label for="stream0-video-framerate" class="col-sm-3 control-label">输出帧率</label>
            <div class="col-sm-8">
                <el-input-number id="stream0-video-framerate" v-model.number="VideoFramerate" :min="10" :max="50" size="small"></el-input-number>
                <span>&nbsp;&nbsp;fps</span>
                <span class="help-block">{{errors.first('stream0.VideoFramerate')}}</span>
            </div>
        </div>
        <div :class="['form-group' , {'has-error': errors.has('stream0.VideoBitrate')}]">
            <label for="stream0-video-bitrate" class="col-sm-3 control-label">输出码率</label>
            <div class="col-sm-8">
                <el-input-number id="stream0-video-bitrate" v-model.number="VideoBitrate" :min="256" :max="4096" size="small"></el-input-number>
                <span>&nbsp;&nbsp;Kbps</span>
                <span class="help-block">{{errors.first('stream0.VideoBitrate')}}</span>
            </div>
        </div>
        <div :class="['form-group' , {'has-error': errors.has('stream0.GridBorder')}]">
            <label for="stream0-grid-border" class="col-sm-3 control-label">边框大小</label>
            <div class="col-sm-8">
                <el-input-number id="stream0-grid-border" v-model.number="GridBorder" :min="0" :max="10" size="small"></el-input-number>
                <span v-if="!GridBorder">&nbsp;&nbsp;不画边框</span>
                <span v-else>&nbsp;&nbsp;像素</span>
                <span class="help-block">{{errors.first('stream0.GridBorder')}}</span>
            </div>
        </div>
        <div :class="['form-group' , {'has-error': errors.has('stream0.Channels')}]">
            <label for="stream0-channels" class="col-sm-3 control-label">合并通道</label>
            <div class="col-sm-8">
                <el-radio-group v-model="channelMode" size="small">
                    <el-radio-button label="single">逐个配置</el-radio-button>
                    <el-radio-button label="range">批量配置</el-radio-button>
                </el-radio-group>
                <span v-if="channelMode == 'range'">&nbsp;&nbsp;通道 {{channelRange[0]}} ~ {{channelRange[1]}}</span>
                <table style="margin: 10px 0;">
                    <tr v-for="(idx, row) in GridRow" :key="row">
                        <td v-for="(idx, col) in GridCol" :key="col" width="160" height="90"
                            :style="`border:${GridBorder}px solid white;`"
                            style="background-color:black;vertical-align:middle;text-align:center;position:relative;">
                            <input type="text" style="width:50px;padding:2px;line-height:100%;text-align:center;" v-if="channelMode == 'single'" @focus="onGridInputFocus"
                                oninput="value=value.replace(/[^\d]/g,'')" v-model.trim.number="channelList[row*GridCol + col]" placeholder="通道?">
                            <span style="color:white;" v-if="channelMode == 'range'">
                                <span v-if="row*GridCol + col <= (channelRange[1] - channelRange[0])">
                                    {{row*GridCol + col + channelRange[0]}}
                                </span>
                                <span v-else>
                                    通道?
                                </span>
                            </span>
                        </td>
                    </tr>
                </table>
                <p v-if="channelMode == 'range'" style="margin: 10px 0;">
                    <el-slider v-model="channelRange" range :min="1" :max="serverInfo.ChannelCount"></el-slider>
                </p>
                <span class="help-block">{{errors.first('stream0.Channels')}}</span>
            </div>
        </div>
        <div :class="['form-group' , {'has-error': errors.has('stream0.Name')}]">
            <label for="stream0-name" class="col-sm-3 control-label">通道名称</label>
            <div class="col-sm-8">
                <input type="text" id="stream0-name" class="form-control" name="Name" data-vv-as="通道名称" v-validate="'required'" v-model.trim="Name">
                <span class="help-block">{{errors.first('stream0.Name')}}</span>
            </div>
        </div>
        <div :class="['form-group' , {'has-error': errors.has('stream0.GBID')}]">
            <label for="stream0-gbid" class="col-sm-3 control-label">国标编号</label>
            <div class="col-sm-8">
                <input type="text" id="stream0-gbid" class="form-control" name="GBID" data-vv-as="国标编号" v-model.trim="GBID" placeholder="可选 不填表示不作国标级联">
                <span class="help-block">{{errors.first('stream0.GBID')}}</span>
            </div>
        </div>
        <div :class="['form-group' , {'has-error': errors.has('stream0.GBID2')}]">
            <label for="stream0-gbid2" class="col-sm-3 control-label">国标(二)编号</label>
            <div class="col-sm-8">
                <input type="text" id="stream0-gbid2" class="form-control" name="GBID2" data-vv-as="国标(二)编号" v-model.trim="GBID2" placeholder="可选 不填表示不作国标(二)级联">
                <span class="help-block">{{errors.first('stream0.GBID2')}}</span>
            </div>
        </div>
        <div :class="['form-group' , {'has-error': errors.has('stream0.Description')}]">
            <label for="stream0-description" class="col-sm-3 control-label">备注</label>
            <div class="col-sm-8">
                <el-input id="stream0-description" type="textarea" v-model.trim="Description" :autosize="{minRows:3, maxRows:5}" :rows="3" placeholder="可选"></el-input>
                <span class="help-block">{{errors.first('stream0.Description')}}</span>
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-offset-3 col-sm-8 checkbox">
                <el-checkbox id="stream0-enable" style="margin-left:-19px;margin-top:-5px;" size="small" v-model.trim="Enable" name="Enable">
                    启用零通道
                </el-checkbox>
                &nbsp;&nbsp;&nbsp;&nbsp;
                <button type="submit" class="btn btn-primary" :disabled="isStream0NoChange || errors.any('stream0') || bCommitting">保存</button>
            </div>
        </div>
    </form>
</div>
</template>

<script>
import $ from "jquery";
import { mapState } from "vuex";

export default {
    data() {
        return {
            bCommitting: false,
            Name: "",
            GBID: "",
            GBID2: "",
            Description: "",
            Channels: "",
            GridCol: 2,
            GridRow: 2,
            GridBorder: 1,
            VideoWidth: 960,
            VideoHeight: 540,
            VideoFramerate: 25,
            VideoBitrate: 1024, // Kbps
            Enable: false,
            gridSize: "2x2",
            gridSizeList: ["2x1", "2x2", "3x2", "3x3", "4x4"],
            videoSize: "960x540",
            videoSizeList: ["640x360", "960x360", "1280x360", "960x540", "1280x720", "1920x1080"],
            remoteStream0Data: "",
            channelMode: "single",
            channelRange: [1, 10],
            channelList: [],
        }
    },
    mounted() {
        this.channelRange[1] = this.serverInfo.ChannelCount || 10;
        this.getStream0Config();
    },
    watch: {
        gridSize: function(newVal, oldVal) {
            var list = newVal.split(/\s*x\s*/);
            if(list.length === 2) {
                var col = parseInt(list[0]);
                var row = parseInt(list[1]);
                if(col && row) {
                    this.GridCol = col;
                    this.GridRow = row;
                }
            }
        },
        videoSize: function(newVal) {
            var list = newVal.split(/\s*x\s*/);
            if(list.length === 2) {
                var w = parseInt(list[0]);
                var h = parseInt(list[1]);
                if(w && h) {
                    this.VideoWidth = w;
                    this.VideoHeight = h;
                }
            }
        },
    },
    methods: {
        async onStream0Submit() {
            var ok = await this.$validator.validateAll('stream0');
            if (!ok) {
                var e = this.errors.items[0];
                this.$message({
                    type: "error",
                    message: e.msg
                });
                $(`[name=${e.field}]`).focus();
                return;
            }
            this.bCommitting = true;
            $.get("/api/v1/stream0/setconfig", this.getStream0CommitObject()).then(data => {
                if ((data.LiveQing || data.NVR).Header.ErrorNum == 200) {
                    this.$message({
                        type: "success",
                        message: "配置成功！"
                    });
                    this.getStream0Config();
                } else {
                    this.$message({
                        type: "error",
                        message: "配置失败！"
                    });
                }
            }).always(() => {
                this.bCommitting = false;
            })
        },
        getStream0CommitObject() {
            switch(this.channelMode) {
                case "single":
                    var size = this.GridCol * this.GridRow;
                    if(size > 0 && this.channelList.length > size) {
                        this.Channels = this.channelList.slice(0, size).join(",");
                    } else {
                        this.Channels = this.channelList.join(",");
                    }
                    break;
                case "range":
                default:
                    var start = this.channelRange[0];
                    var end = this.channelRange[1];
                    if(start > end) {
                        var tmp = end;
                        start = end;
                        end = tmp;
                    }
                    this.Channels = `${start}-${end}`;
            }
            return {
                Name: this.Name,
                GBID: this.GBID,
                GBID2: this.GBID2,
                Description: this.Description,
                Channels: this.Channels,
                GridCol: this.GridCol,
                GridRow: this.GridRow,
                GridBorder: this.GridBorder,
                VideoWidth: this.VideoWidth,
                VideoHeight: this.VideoHeight,
                VideoFramerate: this.VideoFramerate,
                VideoBitrate: this.VideoBitrate,
                Enable: this.Enable,
            };
        },
        getStream0Config() {
            $.get("/api/v1/stream0/config").then(ret => {
                var body = (ret.LiveQing || ret.NVR).Body;
                if (!body) return;
                this.Name = body.Name || "多路合并";
                this.GBID = body.GBID || "";
                this.GBID2 = body.GBID2 || "";
                this.Description = body.Description || "";
                this.Channels = body.Channels || "";
                this.GridCol = body.GridCol || 2;
                this.GridRow = body.GridRow || 2;
                this.GridBorder = body.GridBorder || 0;
                this.VideoWidth = body.VideoWidth || 960;
                this.VideoHeight = body.VideoHeight || 540;
                this.VideoFramerate = body.VideoFramerate || 25;
                this.VideoBitrate = body.VideoBitrate || 1024;
                this.Enable = !!body.Enable;

                if(body.GridSizeList) {
                    this.gridSizeList = body.GridSizeList;
                }
                if(body.VideoSizeList) {
                    this.videoSizeList = body.VideoSizeList;
                }

                this.gridSize = `${this.GridCol}x${this.GridRow}`;
                if(this.gridSizeList.indexOf(this.gridSize) < 0) {
                    this.gridSizeList.push(this.gridSize);
                }

                this.videoSize = `${this.VideoWidth}x${this.VideoHeight}`;
                if(this.videoSizeList.indexOf(this.videoSize) < 0) {
                    this.videoSizeList.push(this.videoSize);
                }

                if(this.Channels) {
                    this.channelList = [];
                    this.channelMode = "single";
                    var list = this.Channels.split(/\s*,\s*/);
                    for(var val of list) {
                        var range = val.split(/\s*-\s*/);
                        if(range.length === 2) {
                            var start = parseInt(range[0])||0;
                            var end = parseInt(range[1])||0;
                            if(start > end) {
                                var tmp = end;
                                end = start;
                                start = tmp;
                            }
                            this.channelMode = "range";
                            this.channelRange = [start, end];
                            for(var i = start; i <= end; i++) {
                                this.channelList.push(i);
                            }
                        } else {
                            this.channelList.push(parseInt(val)||'');
                        }
                    }
                }

                this.remoteStream0Data = JSON.stringify(this.getStream0CommitObject());
            });
        },
        onGridSizeChange() {
            switch(this.gridSize) {
                case "2x1":
                    this.videoSize = "1280x360";
                    break;
                case "3x2":
                    this.videoSize = "960x360";
                    break;
                default:
                    if(this.GridCol != this.GridRow && (this.videoSize === "1280x360" || this.videoSize === "960x360")) {
                        this.videoSize = "960x540";
                    }
                    break;
            }
        },
        onGridInputFocus(e) {
            (e.currentTarget || e.target).select();
        },
    },
    computed: {
        ...mapState([ "serverInfo" ]),
        isStream0NoChange() {
            var localeData = JSON.stringify(this.getStream0CommitObject());
            return this.remoteStream0Data.localeCompare(localeData) == 0;
        }
    }
}
</script>
